﻿using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Bookvar.ObjectModel;

namespace BookvarWpf.Windows.Collaboration
{
    /// <summary>
    /// Interaction logic for CollaborationChat.xaml
    /// </summary>
    public partial class CollaborationChat : BookvarToolWindow, ICollaborationChatView
    {
        private readonly ICollaborationChatPresenter presenter;

        public CollaborationChat()
        {
            InitializeComponent();

            presenter = new CollaborationChatPresenter( this );

            userMessageTextBox.PreviewKeyDown += OnUserMessageTextBoxPreviewKeyDown;
            Closed += OnClosed;
        }

        #region ICollaborationChatView Members

        public void UserSaid( CollaborationUser user, string message )
        {
            if ( Dispatcher.CheckAccess() )
            {
                ShowMessage( user, message );
            }
            else
            {
                Dispatcher.BeginInvoke( DispatcherPriority.Normal,
                                        new Action<CollaborationUser, string>( UserSaid ),
                                        user,
                                        message );
            }
        }

        #endregion

        private void OnClosed( object sender, RoutedEventArgs e )
        {
            CloseCommand.Execute( null, this );
        }

        private void OnUserMessageTextBoxPreviewKeyDown( object sender, KeyEventArgs e )
        {
            if ( e.Key == Key.Enter || e.Key == Key.Return )
            {
                SendMessage();
                e.Handled = true;
            }
        }

        private void SendMessage()
        {
            presenter.SendMessage( userMessageTextBox.Text );
            userMessageTextBox.Clear();
        }

        private void ShowMessage( CollaborationUser sender, string message )
        {
            var messageText = new Run( message );
            var userNameText = new Run( sender.Name + ": " );

            userNameText.Foreground = new SolidColorBrush(
                Color.FromArgb( sender.UserColor.A, sender.UserColor.R, sender.UserColor.G, sender.UserColor.B ) );

            var paragraph = new Paragraph( userNameText );
            paragraph.Inlines.Add( messageText );


            chatLogTextBox.Document.Blocks.Add( paragraph );

            logScrollViewer.PageDown();
        }
    }
}